var qs = require('querystring')
var axios = require('axios')

var redis = require('redis')
var client = redis.createClient()

client.on('error',function(err){
    console.log(err)
})

// 获取token
async function getToken(){


    return new Promise(function(resolve,reject){
        // 先从redis缓存中获取token
        client.get('token',async (err,res) =>{

            if(err){
                reject(err)
            }else{
                if(res){
                    resolve(res)
                }else{

                    //获取一个新的token
                    let result = await getNewToken()
                    console.log(result)
                    client.set('token',result.data.access_token,'EX',result.data.expires_in);
                    resolve(result.data.access_token)
                }
            }
        })

    })

}


async function getNewToken(){
    const param = qs.stringify({
        'grant_type': 'client_credentials',
        'client_id': 'x8D7qv6hl8cbCvsifTpG7ae4',
        'client_secret': 'bg8icgZPYo1pLsve81SG0lQypxwQorVA'
    })
    // 请求接口，获得token
    return axios.get('https://aip.baidubce.com/oauth/2.0/token?' + param)
}

module.exports = getToken;